package cat.joronya.supermanager;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.home.HomeActivity;
import cat.joronya.supermanager.service.LoginHandler;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;

/**
 * Acitivitat inicial, l'splash screen on fem primeres
 * inicialitzacions a l'app.
 * 
 * @author pol
 */
public class SplashActivity extends Activity 
{
	private static final String TAG = "supermanager";
	
	private static final int DIALOG_INTERNET = 0;
	private static final int DIALOG_FIRST_TIME = 1;
	private static final int PROGRESS_FIRST_TIME = 2;
	private static final int DIALOG_LOGIN = 3;
	private static final int DIALOG_FIRST_TIME_CLOSED_WEB = 4;
	
	// dialeg mostrat
	private int dialogShown = -1;
	
	// per executar el service des del dialog
	protected Intent serviceIntent = null;
	
	// the progress dialog
	ProgressDialog progress = null;
	
	// status retornat pel service
	protected int status = -1;
	
	// el loading de recursos a mostrar al progress
	//protected String loading = "";
	
	// variable per saber si feiem login o intialSync
	protected boolean isRequestInitialSync = false;
	
	/** 
	 * Inicialitzem el service, mirem si tenim dades de connexio
	 * i mostrem splash.
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        
        // primer progress dialog loading message
        //loading = getResources().getString(R.string.splash_dialog_authenticating);
        
        // preparem el dir de cache a SD
        File cacheDir;
        if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) )
            cacheDir = new File(Environment.getExternalStorageDirectory(),Supermanager.CACHE_DIR);
        else
            cacheDir = this.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
        
        // preparem fitxer ".nomedia", pq el MediaScanner no trobi els fitxers
        File nomediaFile = new File(cacheDir,".nomedia");
        if(!nomediaFile.exists())
        	try{nomediaFile.createNewFile();}catch(IOException e){}
        
   		// mirem si tenim user/password a les preferences
        SharedPreferences settings = 
    		PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        final String username = settings.getString("username", null);
   		final String password = settings.getString("password", null);

   		// el primer cop no tenim res, les hem de demanar
   		// usuari i password per inicialitzar dades
   		// (primer login, )
   		if( username == null && password == null)
   		{
   			Log.d(TAG, "no tenim user/passwd per tant primer cop i demanem dades");
   			
   			// si no hi ha internet, demanar que es connectin
   			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
   			try
   			{
   				// first start, hide splash progress
   				TextView splashTextView = (TextView)findViewById(R.id.splash_loading);
   				splashTextView.setVisibility(View.GONE);
   				ProgressBar splashProgress = (ProgressBar)findViewById(R.id.splash_progressbar);
   				splashProgress.setVisibility(View.GONE);
   				
   				boolean online = cm.getActiveNetworkInfo().isConnectedOrConnecting();
   				if( !online )
   				{
   					showDialog(DIALOG_INTERNET);
   					dialogShown = DIALOG_INTERNET;
   				}
   				else
   				{
   					showDialog(DIALOG_FIRST_TIME);
   					dialogShown = DIALOG_FIRST_TIME;
   				}
   			}catch(Exception e){
   				// si no tenim ni connectivitat salta NullPointerException
   				showDialog(DIALOG_INTERNET);
   				dialogShown = DIALOG_INTERNET;
   			}
   		}
   		else
   		{
   			// arranquem el service amb el helper
   			SupermanagerServiceHelper.getInstance(SplashActivity.this).login(username, password, loginHandler);
        }
    }
    
    /**
     * Metode on creem el/s dialeg de la activity.
     * Nomes en tenim un, passem del id.
     */
    @Override
    public Dialog onCreateDialog(int id)
    {
    	switch(id)
    	{
    		case DIALOG_INTERNET:
    			AlertDialog.Builder builder = new AlertDialog.Builder(this);
    			builder.setTitle(R.string.splash_alert_title)
    				.setMessage(R.string.splash_alert_message)
    				.setCancelable(false)
    				.setPositiveButton(getResources().getString(R.string.splash_dialog_exit), new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		        	// Perform action on click
       					Log.d("supermanager","clicant exit...");
       					System.exit(0);
    		           }
    		       });
    			return builder.create();
    		
    		case DIALOG_LOGIN:
    			final Dialog dialogLogin = new Dialog(this);
    			dialogLogin.setContentView(R.layout.login);
    			dialogLogin.setTitle(R.string.login_title);
    	
    			final Button loginLogin = (Button) dialogLogin.findViewById(R.id.login_login);
    			loginLogin.setOnClickListener(new View.OnClickListener() {
    				public void onClick(View v) {
    					// Perform action on click
    					Log.d(TAG,"clicant login...");
    					EditText userEditText = ((EditText)dialogLogin.findViewById(R.id.login_username));
    					final String username = userEditText.getText().toString();
    					EditText passEditText = ((EditText)dialogLogin.findViewById(R.id.login_password));
    					final String password = passEditText.getText().toString();
    					
    					// tanquem el primer dialog
    					if( dialogShown == DIALOG_LOGIN )
    						dismissDialog(DIALOG_LOGIN);
    					
    			    	// ocultem el teclat
    			    	InputMethodManager imm = (InputMethodManager)getSystemService(
    			    		      Context.INPUT_METHOD_SERVICE);
    			    	imm.hideSoftInputFromWindow(passEditText.getWindowToken(), 0);
    					
    					// arraquem el progress de loading...
    					showDialog(PROGRESS_FIRST_TIME);
    					dialogShown = PROGRESS_FIRST_TIME;
    		   	        
    					SharedPreferences settings = 
    	        			PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    					SharedPreferences.Editor editor = settings.edit();
    				    editor.putString("username", username);
    				    editor.putString("password", password);

    				    // Commit the edits!
    				    editor.commit();
    				    
       					// arranquem el service amb el helper, cridem login inicial
    	    		   	SupermanagerServiceHelper.getInstance(SplashActivity.this).login(username,password,loginHandler);
    				}
    			});

    			final Button exitLogin = (Button) dialogLogin.findViewById(R.id.login_exit);
    			exitLogin.setOnClickListener(new View.OnClickListener() {
    				public void onClick(View v) {
    					// Perform action on click
    					Log.d(TAG,"clicant exit...");
    					System.exit(0);
    				}
    			});
    	    	return dialogLogin;
    			
    		case PROGRESS_FIRST_TIME:
    			progress = ProgressDialog.show(this, "", 
    				getResources().getString(R.string.splash_dialog_authenticating), true);
    			progress.setCancelable(false);
    			dialogShown = PROGRESS_FIRST_TIME;
    			return progress;
    		
    		case DIALOG_FIRST_TIME_CLOSED_WEB:
    			final Dialog dialogClosedWeb = new Dialog(this);
    			dialogClosedWeb.setContentView(R.layout.error);
    			dialogClosedWeb.setTitle(R.string.error_title);
    			
    			final Button exitError = (Button) dialogClosedWeb.findViewById(R.id.error_exit);
    			exitError.setOnClickListener(new View.OnClickListener() {
    				public void onClick(View v) {
    					// Perform action on click
    					Log.d(TAG,"clicant exit...");
    					System.exit(0);
    				}
    			});
    			return dialogClosedWeb;
    			
    		case DIALOG_FIRST_TIME:
    		default:
    			// marquem q estem fent un first time sync
    			isRequestInitialSync = true;
    			
        		final Dialog dialogFirstTime = new Dialog(this);
        		dialogFirstTime.setContentView(R.layout.first_start);
        		dialogFirstTime.setTitle(R.string.splash_dialog_title);
    	
    			final Button loginFirstTime = (Button) dialogFirstTime.findViewById(R.id.splash_dialog_login);
    			loginFirstTime.setOnClickListener(new View.OnClickListener() {
    				public void onClick(View v) {
    					// Perform action on click
    					Log.d(TAG,"clicant login...");
    					final String username = ((EditText)dialogFirstTime.findViewById(R.id.splash_dialog_username)).getText().toString();
    					EditText passEditText = (EditText)dialogFirstTime.findViewById(R.id.splash_dialog_password);
    					final String password = passEditText.getText().toString();
    					
    					// tanquem el primer dialog
    					if( dialogShown == DIALOG_FIRST_TIME )
    						dismissDialog(DIALOG_FIRST_TIME);
    					
    					// amaguem el teclat
    					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    					imm.hideSoftInputFromWindow(passEditText.getWindowToken(), 0);
    					
    					// arraquem el progress de loading...
    					showDialog(PROGRESS_FIRST_TIME);
    					dialogShown = PROGRESS_FIRST_TIME;
    		   	        
    					SharedPreferences settings = 
    	        			PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    				    SharedPreferences.Editor editor = settings.edit();
    				    editor.putString("username", username);
    				    editor.putString("password", password);

    				    // Commit the edits!
    				    editor.commit();
    				    
    				    // arranquem el service amb el helper, cridem login
    		   			SupermanagerServiceHelper.getInstance(SplashActivity.this).login(username, password, loginHandler);
    				}
    			});

    			final Button exitFirstTime = (Button) dialogFirstTime.findViewById(R.id.splash_dialog_exit);
    			exitFirstTime.setOnClickListener(new View.OnClickListener() {
    				public void onClick(View v) {
    					// Perform action on click
    					Log.d(TAG,"clicant exit...");
    					System.exit(0);
    				}
    			});
    	    	return dialogFirstTime;
    	}
    	
    }
    
    // handler per accio de login (first login o normal)
    private LoginHandler loginHandler = new LoginHandler()
    {
		@Override
		public void closedWeb() 
		{
        	// parem progress
        	if( dialogShown == PROGRESS_FIRST_TIME )
        		dismissDialog(PROGRESS_FIRST_TIME);
        	
        	// si feiem intial sync, mostrem first time,  altrament localment
        	if( isRequestInitialSync )
        	{
        		// error, no podem tenir cap dada
        		showDialog(DIALOG_FIRST_TIME_CLOSED_WEB);
        		dialogShown = DIALOG_FIRST_TIME_CLOSED_WEB;
        	}
        	else
        	{
        		// finalment, marxem a la primera activity de veritat
   				startActivity(new Intent(SplashActivity.this, HomeActivity.class));
        	}
		}

		@Override
		public void openWebNoChanges() 
		{
			// parem progress
        	if( dialogShown == PROGRESS_FIRST_TIME )
        		dismissDialog(PROGRESS_FIRST_TIME);
        	
        	// finalment, marxem a la primera activity de veritat
   			startActivity(new Intent(SplashActivity.this, HomeActivity.class));
		}

		@Override
		public void openWeb() 
		{
			// parem progress
        	if( dialogShown == PROGRESS_FIRST_TIME )
        		dismissDialog(PROGRESS_FIRST_TIME);
        	
        	// finalment, marxem a la primera activity de veritat
   			startActivity(new Intent(SplashActivity.this, HomeActivity.class));
		}

		@Override
		public void authError() 
		{
        	// parem progress
        	if( dialogShown == PROGRESS_FIRST_TIME )
        		dismissDialog(PROGRESS_FIRST_TIME);
        	
        	// si feiem intial sync, mostrem first time, altrament login
        	if( isRequestInitialSync )
        	{
        		// mostrar toast de AUTH error
        		Toast.makeText(SplashActivity.this, R.string.splash_toast_auth_error, Toast.LENGTH_LONG).show();
        		showDialog(DIALOG_FIRST_TIME);
        		dialogShown = DIALOG_FIRST_TIME;
        	}
        	else
        	{
        		showDialog(DIALOG_LOGIN);
        		dialogShown = DIALOG_LOGIN;
        	}
		}

		@Override
		public void otherError() 
		{
        	// parem progress
        	if( dialogShown == PROGRESS_FIRST_TIME )
        		dismissDialog(PROGRESS_FIRST_TIME);
        	
        	// si feiem intial sync, mostrem first time,  altrament localment
        	if( isRequestInitialSync )
        	{
        		// mostrar toast unknown error
        		Toast.makeText(SplashActivity.this, R.string.splash_toast_unknown_error, Toast.LENGTH_LONG).show();
        		showDialog(DIALOG_FIRST_TIME);
        		dialogShown = DIALOG_FIRST_TIME;
        	}
        	else
        	{
        		// finalment, marxem a la primera activity de veritat
   				startActivity(new Intent(SplashActivity.this, HomeActivity.class));
        	}
		}

		@Override
		public void connectivityError() 
		{
        	// parem progress
        	if( dialogShown == PROGRESS_FIRST_TIME )
        		dismissDialog(PROGRESS_FIRST_TIME);
        	
        	// si feiem intial sync, mostrem first time, altrament localment
        	if( isRequestInitialSync )
        	{
        		//  mostar toast error connectivitat
        		Toast.makeText(SplashActivity.this, R.string.splash_toast_conn_error, Toast.LENGTH_LONG).show();
        		showDialog(DIALOG_FIRST_TIME);
        		dialogShown = DIALOG_FIRST_TIME;
        	}
        	else
        	{
        		// finalment, marxem a la primera activity de veritat
   				startActivity(new Intent(SplashActivity.this, HomeActivity.class));
        	}
		}
    };    
}